package terra.managers;

import terra.Config;
import terra.definitions.Biom;
import terra.model.Weather;
import terra.model.map.Map;
import terra.util.MathUtil;

public class WeatherManager implements Runnable {

	static WeatherManager instance;

	public WeatherManager() {
		ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(this, 1000,
				1000);
	}

	@Override
	public void run() {
		long current = System.currentTimeMillis();
		for (Map m : MapManager.getInstance().getMaps().values()) {
			if (m.active && current > m.weather.startedTime + m.weather.time)
				changeWeather(m);
		}
	}

	private void changeWeather(Map m) {
		int chance = MathUtil.rnd.nextInt(Config.MAX_CHANCE);
		Biom b = DefManager.bioms.get(m.getBiomId());
		for (int id : b.weathers.keySet()) {
			if (chance < b.weathers.get(id)) {
				Weather w = new Weather(DefManager.weatherDefs.get(id));
				w.lightIntense = MathUtil.getRndFloat(w.def.minDayLighting,
						w.def.maxDayLighting);
				w.intensity = MathUtil.getRndFloat(w.def.minIntensity,
						w.def.maxIntensity);
				w.time = MathUtil.getRndLong(w.def.minTime, w.def.maxTime);
				m.weather = w;
				m.setWeather(w, true);
				return;
			}
		}
		Weather w = new Weather(DefManager.weatherDefs.get(0));
		w.lightIntense = 1f;
		w.intensity = 0;
		w.time = MathUtil.getRndLong(w.def.minTime, w.def.maxTime);
		m.setWeather(w, true);
	}

	/** Выбрать погоду новой карте, исходя из её биома, и шанса. */
	public void mapCreated(Map m) {
		Weather w = new Weather(DefManager.weatherDefs.get(MathUtil.rnd
				.nextInt(DefManager.weatherDefs.size())));
		w.lightIntense = MathUtil.getRndFloat(w.def.minDayLighting,
				w.def.maxDayLighting);
		w.intensity = MathUtil.getRndFloat(w.def.minIntensity, w.def.maxIntensity);
		w.time = MathUtil.getRndLong(w.def.minTime, w.def.maxTime);
		m.setWeather(w, false);
	}

	public static WeatherManager getInstance() {
		if (instance == null)
			return instance = new WeatherManager();
		return instance;
	}
}
